import { useEffect, useMemo, useState } from "react";
import useGlobalConext from "../GlobalContext";
import api from "../request";
import { Button, FormCheck, Modal } from "react-bootstrap";
import { Form } from "react-router-dom";

function CollectionModal({ poemId, showModal = true, onClose = () => {}, onConfirm = () => {} }) {
    const [context, dispatch] = useGlobalConext();
    const [collections, setCollections] = useState([]);

    useEffect(() => {
        if (!showModal) return;
        api.listCollectionsWithPoem(poemId, (err, data, res) => {
            if (err) {
                console.error(err);
                return;
            }
            setCollections(data.data.collections);
        });
    }, [showModal]);

    return (
        <Modal show={showModal} onHide={onClose}>
            <Modal.Header closeButton>
                <Modal.Title>我的收藏</Modal.Title>
            </Modal.Header>
            <Modal.Body>
                <ul style={{ listStyle: 'none', paddingLeft: '20px' }}>
                    {collections.map(collection => (
                        <div>
                            <li key={collection.id}>  
                                <FormCheck
                                    type="checkbox"
                                    checked={collection.collected}
                                    label={collection.name}
                                    onChange={e => setCollections(collections.map(c => c.id === collection.id ? { ...c, collected: e.target.checked } : c))}
                                />
                            </li>
                        </div>
                    ))}
                </ul>
                {collections.length === 0 && <p>什么都没有哦</p>}
            </Modal.Body>
            <Modal.Footer>
                <Button variant="primary" className="mx-auto" onClick={ () => onConfirm(collections) }>确定</Button>
            </Modal.Footer>
        </Modal>
    );
}


function useCollectionModal(updatedCallback = () => {}) {
    const [showModal, setShowModal] = useState(false);
    const [modalPoemId, setModalPoemId] = useState(null);
    const CollectionModalWrapper = useMemo(
        () => <CollectionModal showModal={showModal} poemId={modalPoemId} onClose={hide} onConfirm={confirm} />,
    [showModal, modalPoemId]);
    
    function confirm(collections) {
        api.batchEditPoem({ poemId: modalPoemId, collections: collections }, (err, data, _) => {
            if (err) throw err;
            updatedCallback();
        });
        hide();
    }
    
    function show(poemId) { setModalPoemId(poemId); setShowModal(true); }
    function hide() { setShowModal(false); }

    return [CollectionModalWrapper, show, hide];
}

export default CollectionModal;
export { useCollectionModal };